import API from './index.js'
import store from "../store";
import Cookies from 'js-cookie' ;
/**
 * 获取令牌
 */
export async function getToken() {
    // 获取 是否 记住 我
    let token = Cookies.get("RBAC-TOKEN") ; // 不能使用 store.getters (失效后有缓存效果)
    let refreshToken = store.getters.refreshToken;

    if (token != null && sessionStorage.getItem("RBAC-USER") == null) {
        store.commit("removeCookie");
        token = null ;
    }
    if ((token == null && refreshToken != null)) {
        let ret = await API.refresh(refreshToken);
        if (ret.data.status) {
            token = ret.data.accessToken;
            store.commit("setUserAndAuthorities", {
                user: ret.data.user,
                auth: ret.data.authorities,
                token: ret.data.accessToken,
                rememberMe: localStorage.getItem("RBAC-REFRESH-TOKEN") != null,
                refresh: ret.data.refreshToken,
                exp: ret.data.exp ,
            });
        } else { // 如果接口调用失败，将接口的失败信息抛出去
            let error = new Error("刷新接口调用失败");
            error.response = data;
            throw error;
        }
    }
    store.state.token = token ; // 为文件上传服务的代码
    return token ;
}

